# AIQuant 测试环境配置
# 专为自动化测试优化的配置

import os
from typing import List, Optional
from pydantic import BaseSettings, validator
from datetime import timedelta

class TestingSettings(BaseSettings):
    """测试环境配置类"""
    
    # =============================================================================
    # 基础配置
    # =============================================================================
    ENVIRONMENT: str = "testing"
    DEBUG: bool = True
    TESTING: bool = True
    
    # 应用信息
    APP_NAME: str = "AIQuant-Test"
    APP_VERSION: str = "1.0.0-test"
    APP_DESCRIPTION: str = "AI-powered Quantitative Investment Research System (Testing)"
    
    # =============================================================================
    # 服务器配置
    # =============================================================================
    # API服务器（测试环境使用随机端口）
    API_HOST: str = "127.0.0.1"
    API_PORT: int = 0  # 使用随机可用端口
    API_WORKERS: int = 1
    API_RELOAD: bool = False
    API_LOG_LEVEL: str = "warning"  # 减少测试日志噪音
    
    # Web仪表板（测试环境关闭）
    WEB_HOST: str = "127.0.0.1"
    WEB_PORT: int = 0
    WEB_SERVER_HEADLESS: bool = True
    WEB_SERVER_ENABLE_CORS: bool = True
    WEB_SERVER_ENABLE_XSRF_PROTECTION: bool = False
    
    # =============================================================================
    # 数据库配置
    # =============================================================================
    # 测试数据库（内存数据库或独立测试库）
    DATABASE_URL: str = "postgresql://aiquant:aiquant_test_password@localhost:5432/aiquant_test"
    DATABASE_POOL_SIZE: int = 1
    DATABASE_MAX_OVERFLOW: int = 2
    DATABASE_POOL_TIMEOUT: int = 10
    DATABASE_POOL_RECYCLE: int = 300
    DATABASE_POOL_PRE_PING: bool = False
    DATABASE_ECHO: bool = False  # 测试环境关闭SQL日志
    DATABASE_ECHO_POOL: bool = False
    
    # 数据库连接重试
    DATABASE_RETRY_ATTEMPTS: int = 1
    DATABASE_RETRY_DELAY: int = 1
    
    # 时间序列数据库（测试环境简化）
    TIMESCALE_CHUNK_TIME_INTERVAL: str = "1 minute"
    TIMESCALE_COMPRESSION_ENABLED: bool = False
    
    # 测试数据库配置
    TEST_DATABASE_ISOLATION: bool = True  # 每个测试使用独立事务
    TEST_DATABASE_ROLLBACK: bool = True   # 测试后回滚数据
    
    # =============================================================================
    # Redis配置
    # =============================================================================
    # 测试Redis（使用不同的数据库编号）
    REDIS_URL: str = "redis://localhost:6379/15"  # 使用数据库15进行测试
    REDIS_POOL_SIZE: int = 2
    REDIS_POOL_MAX_CONNECTIONS: int = 5
    REDIS_SOCKET_TIMEOUT: int = 2
    REDIS_SOCKET_CONNECT_TIMEOUT: int = 2
    REDIS_SOCKET_KEEPALIVE: bool = False
    REDIS_HEALTH_CHECK_INTERVAL: int = 60
    
    # =============================================================================
    # Celery配置
    # =============================================================================
    # 测试环境使用同步执行
    CELERY_BROKER_URL: str = "redis://localhost:6379/14"
    CELERY_RESULT_BACKEND: str = "redis://localhost:6379/13"
    CELERY_TASK_SERIALIZER: str = "json"
    CELERY_RESULT_SERIALIZER: str = "json"
    CELERY_ACCEPT_CONTENT: List[str] = ["json"]
    CELERY_TIMEZONE: str = "Asia/Shanghai"
    CELERY_ENABLE_UTC: bool = True
    
    # 测试环境同步执行任务
    CELERY_TASK_ALWAYS_EAGER: bool = True
    CELERY_TASK_EAGER_PROPAGATES: bool = True
    CELERY_WORKER_CONCURRENCY: int = 1
    CELERY_WORKER_PREFETCH_MULTIPLIER: int = 1
    
    # 任务配置
    CELERY_TASK_SOFT_TIME_LIMIT: int = 10
    CELERY_TASK_TIME_LIMIT: int = 20
    CELERY_TASK_ACKS_LATE: bool = False
    CELERY_TASK_REJECT_ON_WORKER_LOST: bool = False
    CELERY_TASK_IGNORE_RESULT: bool = False
    
    # 结果后端配置
    CELERY_RESULT_EXPIRES: int = 300  # 5分钟
    CELERY_RESULT_PERSISTENT: bool = False
    
    # Beat调度器配置（测试环境关闭）
    CELERY_BEAT_SCHEDULE: dict = {}
    
    # =============================================================================
    # 安全配置（测试环境简化）
    # =============================================================================
    SECRET_KEY: str = "test-secret-key-for-testing-only-12345678901234567890"
    JWT_SECRET_KEY: str = "test-jwt-secret-key-for-testing-only-12345678901234567890"
    JWT_ALGORITHM: str = "HS256"
    JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 5  # 测试环境短过期时间
    JWT_REFRESH_TOKEN_EXPIRE_DAYS: int = 1
    
    # CORS配置（测试环境允许所有）
    CORS_ORIGINS: List[str] = ["*"]
    CORS_ALLOW_CREDENTIALS: bool = True
    CORS_ALLOW_METHODS: List[str] = ["*"]
    CORS_ALLOW_HEADERS: List[str] = ["*"]
    
    # 速率限制（测试环境关闭）
    RATE_LIMIT_ENABLED: bool = False
    
    # SSL/TLS配置（测试环境关闭）
    SSL_ENABLED: bool = False
    
    # =============================================================================
    # 日志配置
    # =============================================================================
    LOG_LEVEL: str = "WARNING"  # 测试环境减少日志输出
    LOG_FORMAT: str = "%(levelname)s - %(name)s - %(message)s"
    LOG_DATE_FORMAT: str = "%H:%M:%S"
    
    # 日志文件配置（测试环境关闭文件日志）
    LOG_FILE_ENABLED: bool = False
    
    # 控制台日志
    LOG_CONSOLE_ENABLED: bool = True
    LOG_CONSOLE_LEVEL: str = "ERROR"  # 只显示错误日志
    LOG_CONSOLE_FORMAT: str = "TEST %(levelname)s: %(message)s"
    
    # 结构化日志（测试环境关闭）
    LOG_JSON_FORMAT: bool = False
    LOG_INCLUDE_TRACE_ID: bool = False
    
    # 外部日志服务（测试环境关闭）
    LOG_ELASTICSEARCH_ENABLED: bool = False
    
    # =============================================================================
    # 监控配置（测试环境简化）
    # =============================================================================
    # Prometheus指标（测试环境关闭）
    METRICS_ENABLED: bool = False
    
    # 健康检查
    HEALTH_CHECK_ENABLED: bool = True
    HEALTH_CHECK_PATH: str = "/health"
    HEALTH_CHECK_TIMEOUT: int = 5
    
    # 性能监控（测试环境关闭）
    PERFORMANCE_MONITORING_ENABLED: bool = False
    
    # APM配置（测试环境关闭）
    APM_ENABLED: bool = False
    
    # =============================================================================
    # 缓存配置
    # =============================================================================
    CACHE_ENABLED: bool = False  # 测试环境关闭缓存以确保数据一致性
    CACHE_DEFAULT_TIMEOUT: int = 1
    CACHE_KEY_PREFIX: str = "aiquant:test:"
    
    # =============================================================================
    # 业务配置
    # =============================================================================
    # 市场数据（测试环境使用模拟数据）
    MARKET_DATA_PROVIDERS: List[str] = ["mock"]
    MARKET_DATA_UPDATE_INTERVAL: int = 1
    MARKET_DATA_RETENTION_DAYS: int = 1
    
    # 交易配置
    TRADING_ENABLED: bool = False
    TRADING_MODE: str = "simulation"
    TRADING_COMMISSION_RATE: float = 0.0
    TRADING_SLIPPAGE_RATE: float = 0.0
    
    # 风险管理（测试环境关闭）
    RISK_MONITORING_ENABLED: bool = False
    
    # 智能体配置
    AGENT_MAX_CONCURRENT: int = 1
    AGENT_TIMEOUT: int = 5
    AGENT_RETRY_ATTEMPTS: int = 1
    
    # =============================================================================
    # 外部服务配置（测试环境全部关闭或模拟）
    # =============================================================================
    # 邮件服务（测试环境关闭）
    EMAIL_ENABLED: bool = False
    
    # 消息通知（测试环境关闭）
    NOTIFICATION_ENABLED: bool = False
    
    # 第三方API（测试环境使用模拟）
    OPENAI_API_KEY: Optional[str] = "test-api-key"
    OPENAI_MODEL: str = "mock-model"
    OPENAI_MAX_TOKENS: int = 100
    OPENAI_TEMPERATURE: float = 0.0
    
    # =============================================================================
    # 测试专用配置
    # =============================================================================
    # 测试数据
    USE_TEST_DATA: bool = True
    TEST_DATA_PATH: str = "tests/data"
    MOCK_EXTERNAL_APIS: bool = True
    
    # 测试数据库
    TEST_DATABASE_CLEANUP: bool = True
    TEST_DATABASE_FIXTURES: List[str] = ["basic_data", "market_data", "user_data"]
    
    # 测试缓存
    TEST_CACHE_CLEANUP: bool = True
    
    # 测试文件
    TEST_FILE_CLEANUP: bool = True
    TEST_TEMP_DIR: str = "/tmp/aiquant_test"
    
    # 并发测试
    TEST_CONCURRENT_USERS: int = 5
    TEST_CONCURRENT_REQUESTS: int = 10
    
    # 性能测试
    TEST_PERFORMANCE_ENABLED: bool = False
    TEST_LOAD_USERS: int = 10
    TEST_LOAD_DURATION: int = 30
    
    # 集成测试
    TEST_INTEGRATION_ENABLED: bool = True
    TEST_EXTERNAL_SERVICES: bool = False  # 是否测试外部服务
    
    # 端到端测试
    TEST_E2E_ENABLED: bool = False
    TEST_E2E_BROWSER: str = "headless"
    TEST_E2E_TIMEOUT: int = 30
    
    # =============================================================================
    # Mock配置
    # =============================================================================
    # Mock外部API
    MOCK_MARKET_DATA_API: bool = True
    MOCK_TRADING_API: bool = True
    MOCK_EMAIL_SERVICE: bool = True
    MOCK_NOTIFICATION_SERVICE: bool = True
    MOCK_AI_SERVICE: bool = True
    
    # Mock数据配置
    MOCK_DATA_SEED: int = 42  # 固定随机种子确保测试可重复
    MOCK_DATA_SIZE: int = 100
    MOCK_DATA_DAYS: int = 30
    
    # =============================================================================
    # 性能优化配置
    # =============================================================================
    # 数据库查询优化（测试环境关闭）
    DATABASE_QUERY_CACHE_ENABLED: bool = False
    DATABASE_SLOW_QUERY_LOG: bool = False
    
    # 异步处理
    ASYNC_POOL_SIZE: int = 1
    ASYNC_TIMEOUT: int = 5
    
    # 内存管理
    MEMORY_LIMIT_MB: int = 512
    MEMORY_WARNING_THRESHOLD: float = 0.95
    
    # =============================================================================
    # 备份和恢复（测试环境关闭）
    # =============================================================================
    BACKUP_ENABLED: bool = False
    
    # =============================================================================
    # 验证器（测试环境宽松）
    # =============================================================================
    @validator('SECRET_KEY', 'JWT_SECRET_KEY')
    def validate_secret_keys(cls, v):
        # 测试环境允许测试密钥
        return v
    
    @validator('LOG_LEVEL')
    def validate_log_level(cls, v):
        valid_levels = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
        if v.upper() not in valid_levels:
            raise ValueError(f'LOG_LEVEL must be one of {valid_levels}')
        return v.upper()
    
    class Config:
        env_file = ".env.testing"
        env_file_encoding = "utf-8"
        case_sensitive = True
        
        # 环境变量前缀
        env_prefix = "AIQUANT_TEST_"
        
        # 字段别名
        fields = {
            'DATABASE_URL': {'env': ['TEST_DATABASE_URL', 'DATABASE_URL']},
            'REDIS_URL': {'env': ['TEST_REDIS_URL', 'REDIS_URL']},
        }

# 创建配置实例
settings = TestingSettings()

# 导出常用配置
__all__ = ['settings', 'TestingSettings']